package com.ifast.hnzk.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ifast.common.annotation.Log;
import com.ifast.common.base.BaseController;
import com.ifast.common.utils.Result;
import com.ifast.common.utils.UUIDUtils;
import com.ifast.hnzk.domain.NewsDO;
import com.ifast.hnzk.service.NewsService;
import com.ifast.hnzk.util.FileStreamHelp;
import org.apache.shiro.authz.annotation.RequiresPermissions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * 
 * <pre>
 * 
 * </pre>
 * <small> 2019-06-10 10:56:21 | wch</small>
 */
@Controller
@RequestMapping("/hnzk/news")
public class NewsController extends BaseController {
	private Logger logger = LoggerFactory.getLogger(NewsController.class);

	@Autowired
	private NewsService newsService;
	/**
	 * 保存的静态页面地址
	 */
	@Value("${hnzk_save_template_path}")
	private String hnzk_save_template_path;
	/**
	 * 公司新闻模版
	 */
	@Value("${hnzk_newsThmplate}")
	private String hnzk_newsThmplate;
	/**
	 * 行业新闻模版
	 */
	@Value("${hnzk_newsThmplate2}")
	private String hnzk_newsThmplate2;

	@Autowired
    private FileStreamHelp fileStreamHelp;


	@GetMapping()
	@RequiresPermissions("news:news:news")
	String News(){
	    return "hnzk/news/news";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("news:news:news")

	public Result<Page<NewsDO>> list(NewsDO newsDTO){
		//logger.info("======进入新闻列表页面======");
        Wrapper<NewsDO> wrapper = new EntityWrapper<NewsDO>().orderBy("id", false);
		wrapper.like("title", newsDTO.getTitle());
		wrapper.eq(newsDTO.getType()!=null,"type",newsDTO.getType());
		wrapper.eq(newsDTO.getStatus()!=null,"status",newsDTO.getStatus());
        Page<NewsDO> page = newsService.selectPage(getPage(NewsDO.class), wrapper);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("news:news:add")
	String add(){
	    return "hnzk/news/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("news:news:edit")
	String edit(@PathVariable("id") Long id,Model model){
		NewsDO news = newsService.selectById(id);
		model.addAttribute("news", news);
	    return "hnzk/news/edit";
	}
	
	@Log("添加")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("news:news:add")
	public Result<String> save( NewsDO news){
		if(news != null) {
			news.setCreatetime(new Date());
		}
		newsService.insert(news);
		//生成静态模版页面
		String staticPath = getPStaticPage(news);
		news.setStaticpage(staticPath);
		newsService.updateById(news);
        return Result.ok();
	}
	
	@Log("修改")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("news:news:edit")
	public Result<String>  update( NewsDO news){
		if(news!=null){
			//查看原来是静态页面是否存在，存在即删除掉
			/*String oldStatisPage =news.getStaticpage();
			File oldFile = new File(hnzk_save_template_path+oldStatisPage);
			if(oldFile.exists()){
				oldFile.delete();
			}*/
			//生成静态模版页面
			String staticPath = getPStaticPage(news);
			news.setStaticpage(staticPath);
		}
		boolean update = newsService.updateById(news);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("news:news:remove")
	public Result<String>  remove( Long id){
		newsService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("news:news:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		newsService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}


	@Log("静态模版生成方法")
	public String getPStaticPage(NewsDO newsDO){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String staticPagePath = UUIDUtils.get() +".html";
		String htmlcode = null;
		try{
			if(newsDO.getType() == 0){
				//公司新闻
				htmlcode = fileStreamHelp.ReadFile(hnzk_newsThmplate);//读取模板文件
			}else if(newsDO.getType() == 1){
				//行业新闻
				htmlcode = fileStreamHelp.ReadFile(hnzk_newsThmplate2);//读取模板文件

			}
			htmlcode=htmlcode.replaceAll("###htmltitle###",newsDO.getTitle());
			if(newsDO.getDescription().length()>30){
				htmlcode=htmlcode.replaceAll("###htmlcontent###", newsDO.getDescription().substring(0, 30));
			}else{
				htmlcode=htmlcode.replaceAll("###htmlcontent###", newsDO.getDescription());
			}
			htmlcode=htmlcode.replaceAll("###newtitle###", newsDO.getTitle());
			htmlcode=htmlcode.replaceAll("###newsauthor###", newsDO.getAuthor());
			htmlcode=htmlcode.replaceAll("###newsources###", newsDO.getSources());
			htmlcode=htmlcode.replaceAll("###newstime###", sdf.format(newsDO.getCreatetime()));
			htmlcode=htmlcode.replaceAll("###newscontent###", newsDO.getContent());
			NewsDO newsPrev = newsService.getNewsPrev(newsDO.getId(),newsDO.getType());
			if(newsPrev!=null){
				htmlcode=htmlcode.replaceAll("###newsprev###", "<a href='"+newsPrev.getStaticpage()+"'>"+newsPrev.getTitle()+"</a>");
			}else{
				htmlcode=htmlcode.replaceAll("###newsprev###", "没有新闻了");
			}
			NewsDO newsNext = newsService.getNewsNext(newsDO.getId(),newsDO.getType());
			if(newsNext!=null){
				htmlcode=htmlcode.replaceAll("###newsnext###", "<a href='"+newsNext.getStaticpage()+"'>"+newsNext.getTitle()+"</a>");
			}else{
				htmlcode=htmlcode.replaceAll("###newsnext###", "没有新闻了");
			}
			fileStreamHelp.WriteFile(htmlcode, hnzk_save_template_path+staticPagePath);//生成静态文件
		}catch (Exception e){

			e.printStackTrace();
		}
		return  staticPagePath;
	}
}
